package com.rjyb.feedbackplatform.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

//配置类的注解
//spring扫描器会扫描该注解
//相当于在application.properties中进⾏配置
//整个类就是⼀个spring容器
//@Configuration
public class DruidConfig {
    //从application.properties中获取参数并且赋值给变量
    @Value("${mysql.login.username}")
    private String loginName;
    @Value("${mysql.login.password}")
    private String loginPWD;
    @Value("${mysql.login.url}")
    private String url;
    @Value("${mysql.login.driver}")
    private String driver;

    @Bean //标注这是⼀个spring容器的bean
    @Primary //设置bean的优先级
    //返回值就是bean的类型 ⽅法名就是bean的id
    public DataSource dataSource() {
        //指定使⽤ com.alibaba.druid.pool.DruidDataSource 数据源
        DruidDataSource datasource = new DruidDataSource();
        //数据库连接信息
        datasource.setUrl(url);
        //数据库连接⽤户名和密码
        datasource.setUsername(loginName);
        datasource.setPassword(loginPWD);
        datasource.setDriverClassName(driver);
// datasource.setMaxActive();
// datasource.setMinIdle();
// datasource.setMaxWait();
        try {
            //配置默认拦截
            datasource.setFilters("stat,wall,slf4j");
        } catch (SQLException e) {
        }
        return datasource;
    }

    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean reg = new ServletRegistrationBean();
        reg.setServlet(new StatViewServlet());
        //启⽤监控⻚⾯
        reg.setEnabled(true);
        //配置监控url
        reg.addUrlMappings("/druid/*");
        //设置控制台管理⽤户
        reg.addInitParameter("loginUsername", "root");
        reg.addInitParameter("loginPassword", "123456");
        return reg;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        //创建过滤器
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.setEnabled(true);
        Map<String, String> initParams = new HashMap<String, String>();
        //忽略过滤的形式
        initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css, *.ico,/druid/*");
        filterRegistrationBean.setInitParameters(initParams);
        //设置过滤器过滤路径
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }
}